#include <stdio.h>

#include "cJSON.h"
#include "ds18b20.h"
#include "mosquitto.h"
#include "struct.h"
#include <string.h>
#include <errno.h>

void connect_pub_callback (struct mosquitto *mosq, void *obj, int rc)
{
	cJSON*          cjson_msg = NULL;
	cJSON*          cjson_properties = NULL;
	char*           str;
	double           temp;
	char           *id = "rpi_001";
	int             mid;
	mosquitto_t    *mqtt;

	mqtt = (mosquitto_t *)obj;

	get_temperature(&temp);

	//printf("get tempurature: %.3f\n",temp);

	cjson_msg = cJSON_CreateObject();


	cJSON* cjson_params = cJSON_CreateObject();
	cJSON_AddNumberToObject(cjson_params,"CurrentTemperature",temp);
	cJSON_AddItemToObject(cjson_msg,"params",cjson_params);

	str = cJSON_Print(cjson_msg);

	if(rc==0)
	{
   	  printf("\n-------send information------\n");
    	printf("%s\n", str);


		if(mosquitto_publish(mosq,&mid,mqtt->topic,strlen(str)+1,str,0,true)!=MOSQ_ERR_SUCCESS)
		{

			printf("Mosquitto Pub failure: %s\n",strerror(errno));
			return;
		}

		printf("\n----Published!----\n");
		printf("\n");

	}

	cJSON_Delete(cjson_msg);

	mosquitto_disconnect(mosq);

}

void connect_sub_callback(struct mosquitto *mosq,void *obj,int mid,int qos_count,const int *granted_qos)
{
	int i;
        bool have_subscription = false;

        for(i=0; i<qos_count; i++){
                printf("on_subscribe: %d:granted qos = %d\n", i, granted_qos[i]);
                if(granted_qos[i] <= 2){
                        have_subscription = true;
                }
        }
        if(have_subscription == false){
                fprintf(stderr, "Error: All subscriptions rejected.\n");
                mosquitto_disconnect(mosq);
        }

}

void connect_message_callback(struct mosquitto *mosq,void *obj,const struct mosquitto_message *msg)
{
	printf("\n-------subscribe message-------\n");

	printf("%s\n",msg->payload);
}

void connect_disconnect_callback(struct mosquitto *mosq,void *obj,int rc)
{
	printf("\n-------------------------------\n");

}





